package com.yangyouqi.posthorse.web.controller;

import com.yangyouqi.posthorse.core.domain.Customer;
import com.yangyouqi.posthorse.core.domain.Order;
import com.yangyouqi.posthorse.core.service.OrderService;
import com.yangyouqi.posthorse.web.from.AddForDeliverFrom;
import com.yangyouqi.posthorse.web.from.AddForSellFrom;
import com.yangyouqi.posthorse.web.from.AddForTakeFrom;
import org.aspectj.weaver.ast.Or;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.List;

/**
 * @author 杨友奇
 * @Time 2018/6/27
 */
@Controller
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrderService orderService;


    //进入下单页面
    @GetMapping("/index")
    public String index(HttpSession session, Model model) {
        getsession(session, model, "customer");
        return "order/index";
    }

    /**
     * 進入幫我買下單頁面
     */
    @GetMapping("/addForSell")
    public String addForSell(HttpSession session, Model model) {
        //获取回话信息
        getsession(session, model, "customer");
        return "order/addForSell";
    }

    /**
     * 執行幫我買下單操作，跳轉到跳單成功頁面
     * 幫我買頁面有：商家，姓名，購買物品，聯繫電話
     */
    @PostMapping("/addForSell")
    public String addForSell(@Validated AddForSellFrom addForSellFrom, BindingResult result,
                             HttpSession session, Model model) {
        if (result.hasErrors()) {
            List<ObjectError> list = result.getAllErrors();
            for (ObjectError error : list) {
                model.addAttribute("Msg", error.getDefaultMessage());
                //重新獲取會話信息
                getsession(session, model, "customer");
                return "order/addForSell";
            }
        }
        //1.order数据来自表单
        Order order = new Order();
        order.setStore(addForSellFrom.getStore());
        order.setConsignee(addForSellFrom.getConsignee());
        order.setConsigneeMobile(addForSellFrom.getConsigneeMobile());
        order.setGoods(addForSellFrom.getGoods());
        order.setType(1);

        //2.下单客户ID，数据来源session
        Customer customer = (Customer) session.getAttribute("customer");

        Order result1 = orderService.create(order, customer.getId());

        if (result1 != null) {
            getsession(session, model, "customer");
            return "order/success";
        } else {
            return "publiz/error";
        }
    }

    /**
     * 進入幫我取下單頁面
     */
    @GetMapping("/addForTake")
    public String addForTake(HttpSession session, Model model) {
        //获取回话信息
        getsession(session, model, "customer");

        return "order/addForTake";
    }

    /**
     * 執行幫我取下單操作，跳轉到跳單成功頁面
     * 帮我取页面有：收货人姓名，收货人电话，取货地址，收货物品
     */
    @PostMapping("/addForTake")
    public String addForTake(@Validated AddForTakeFrom addForTakeFrom, BindingResult result,
                             HttpSession session, Model model) {
        if (result.hasErrors()) {
            List<ObjectError> list = result.getAllErrors();
            for (ObjectError error : list) {
                model.addAttribute("Msg", error.getDefaultMessage());
                //重新獲取會話信息
                getsession(session, model, "customer");
                return "order/addForTake";
            }
        }
        Order order = new Order();
        order.setConsignee(addForTakeFrom.getConsignee());
        order.setConsigneeMobile(addForTakeFrom.getConsigneeMobile());
        order.setGoods(addForTakeFrom.getGoods());
        order.setPickupAddress(addForTakeFrom.getPickupAddress());
        order.setType(3);

        Customer customer = (Customer) session.getAttribute("customer");

        Order result1 = orderService.create(order, customer.getId());

        if (result1 != null) {
            getsession(session, model, "customer");
            return "order/success";
        } else {
            return "publiz/error";
        }

    }

    /**
     * 進入幫我送下單頁面
     */
    @GetMapping("/addForDeliver")
    public String addForDeliver(HttpSession session, Model model) {
        //获取回话信息
        getsession(session, model, "customer");
        return "order/addForDeliver";
    }

    /**
     * 執行幫我送下單操作，跳轉到跳單成功頁面
     * 帮我送页面有：收货人姓名，收货人电话，送货物品，送货人姓名，送货人电话，送货人地址
     */
    @PostMapping("/addForDeliver")
    public String addForDeliver(@Validated AddForDeliverFrom deliverFrom, BindingResult result,
                                HttpSession session, Model model) {
        if (result.hasErrors()) {
            List<ObjectError> list = result.getAllErrors();
            for (ObjectError error : list) {
                model.addAttribute("Msg", error.getDefaultMessage());
                //重新獲取會話信息
                getsession(session, model, "customer");
                return "order/addForDeliver";
            }
        }
        Order order = new Order();
        order.setConsignee(deliverFrom.getConsignee());
        order.setConsigneeMobile(deliverFrom.getConsigneeMobile());
        order.setGoods(deliverFrom.getGoods());
        order.setConsigner(deliverFrom.getConsigner());
        order.setConsignerMobiel(deliverFrom.getConsignerMobiel());
        order.setPickupAddresr(deliverFrom.getPickupAddresr());
        order.setType(2);


        Customer customer = (Customer) session.getAttribute("customer");

        Order result1 = orderService.create(order, customer.getId());

        if (result != null) {
            getsession(session, model, "customer");
            return "order/success";
        } else {
            return "publiz/error";
        }
    }

    /**
     * 进入我的订单页面
     *
     * @param start 起始位置
     * @param limit 每页显示多少条记录
     * @param model
     * @return
     */
    @GetMapping("/myOrder")
    public String lists(@RequestParam(defaultValue = "0", value = "start") Integer start,
                        @RequestParam(defaultValue = "10", value = "limit") Integer limit,
                        HttpSession session,
                        Model model) {
        Customer customer = (Customer) session.getAttribute("customer");
        getsession(session, model, "customer");
        Sort sort = new Sort(Sort.DEFAULT_DIRECTION, "id");
        Pageable pageable = new PageRequest(start, limit, sort);
        Page<Order> page = orderService.listForCustomer(customer.getId(), pageable);
        model.addAttribute("page", page);
        return "order/myOrder";
    }

    /**
     * 进入详情页面
     */
    @GetMapping("/detail")
    public String detail(@RequestParam Long id, HttpSession session, Model model) {

        getsession(session, model, "customer");
        Order order = orderService.get(id);
        //保存訂單繪畫信息
        session.setAttribute("order", order);
        model.addAttribute("order", order);

        return "/order/detail";
    }

    /**
     * 客户进入确认收获页面
     */
    @GetMapping("/confirm")
    public String confirm(@RequestParam Long id, HttpSession session, Model model) {

        getsession(session, model, "customer");

        orderService.confirmByCustomer(id);
        return "redirect:/order/detail?id=" + id;
    }

    /**
     * 客户进入评价页面
     */
    @GetMapping("/evaluate")
    public String evaluate(HttpSession session, Model model) {
        getsession(session, model, "customer");
        return "/order/evaluate";

    }



    /**
     * 进入评价内容，提交评价信息
     *
     * @param session
     * @param model
     * @return
     */
    @PostMapping("/evaluate")
    public String evaluate1(@RequestParam String evaluateContent, HttpSession session, Model model) {

        Order order = (Order) session.getAttribute("order");
        Order result = orderService.evaluate(order.getId(), evaluateContent);
        if (result != null) {
            return "redirect:/order/detail?id=" + order.getId();
        } else {
            //评价不成功返回
            return "order/evaluate";
        }
    }

    /**
     * 获取当前配送员配送订单列表
     *
     * @param start
     * @param limit
     * @param session
     * @param model
     * @return
     */
    @GetMapping("/list")
    public String listsForDistributor(@RequestParam(defaultValue = "0", value = "start") Integer start,
                                      @RequestParam(defaultValue = "10", value = "limit") Integer limit,
                                      HttpSession session, Model model) {

        Customer customer = (Customer) session.getAttribute("customer");
        model.addAttribute("customer",customer);
        Sort sort = new Sort(Sort.DEFAULT_DIRECTION, "id");
        Pageable pageable = new PageRequest(start, limit, sort);
        Page<Order> page = orderService.listForDistributor(customer.getId(), pageable);
        model.addAttribute("page", page);
        return "order/list";
    }

    /**
     * 配送员确认送达订单
     * @param id
     * @param model
     * @return
     */
    @GetMapping("/sendTo")
    public String sendTo(@RequestParam Long id,HttpSession session, Model model){
        getsession(session,model,"customer");
        orderService.confirmByDistributor(id);
        //2.再去查询订单信息，跳转到详情页面
        Order order = orderService.get(id);
        model.addAttribute("order", order);
        return "order/senddetail";
    }

    /**
     * 配送员领取订单
     * @param id
     * @param model
     * @return
     */
    @GetMapping("/receipt")
    public String receipt(@RequestParam Long id,HttpSession session, Model model){
        getsession(session,model,"customer");
        orderService.claim(id);
        //2.再去查询订单信息，跳转到详情页面
        Order order = orderService.get(id);
        model.addAttribute("order", order);
        return "order/senddetail";
    }




    /**
     * 获取session信息并返回给前端代码
     *
     * @param session
     * @param model
     * @return
     */
    public static void getsession(HttpSession session, Model model, String key) {
        Customer customer = (Customer) session.getAttribute("customer");
        model.addAttribute(key, customer);
    }
}
